package com.fx.usercenter.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.ser.Serializers;
import com.fx.usercenter.common.BaseResponse;
import com.fx.usercenter.common.ErrorCode;
import com.fx.usercenter.common.ResultUtils;
import com.fx.usercenter.exception.BusinessException;
import com.fx.usercenter.mapper.UserMapper;
import com.fx.usercenter.model.domain.User;
import com.fx.usercenter.model.domain.request.UserLoginRequest;
import com.fx.usercenter.model.domain.request.UserRegisterRequest;
import com.fx.usercenter.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.fx.usercenter.contant.UserConstant.ADMIN_ROLE;
import static com.fx.usercenter.contant.UserConstant.USER_LOGIN_STATE;

/**
 * 用户接口
 */
@Slf4j
@RestController
@RequestMapping(value = "/user")
public class UserController {
   @Resource
   private UserMapper userMapper;
   private UserService userService;
    @PostMapping(value = "/register")
    public BaseResponse <Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest){
        if (userRegisterRequest == null){
           throw new BusinessException(ErrorCode.NO_LOHIN);
        }
        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        String plantCode = userRegisterRequest.getPlanetCode();
        if(StringUtils.isAllBlank(userAccount,userPassword,checkPassword)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long result = userService.UserRegister(userAccount,userPassword,checkPassword,plantCode);
       // return new BaseResponse<>(0,result,"ok");
        return ResultUtils.success(result);
    }
    @PostMapping("/login")
    public User userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {
        if (userLoginRequest == null) {
            return null;
        }
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            return null;
        }
        log.info("出错"+userService.userLogin(userAccount, userPassword, request));
       return userService.userLogin(userAccount, userPassword, request);
       // return ResultUtils.success(user);
    }
    @PostMapping(value = "/logout")
    public BaseResponse <Integer> userLogout(HttpServletRequest request){
        if (request == null){
            return ResultUtils.error(ErrorCode.PARAMS_ERROR);
        }
        int result = userService.userLogout(request);
        return ResultUtils.success(result);
    }
    @GetMapping(value = "/current")
    public BaseResponse <User> searchUsers(HttpServletRequest request){
        /*
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        User currentUser = (User) userObj;
        if(currentUser == null){
             return ResultUtils.error(ErrorCode.PARAMS_ERROR);
        }
       long userId = currentUser.getId();
        //todo 校验用户是否合法
        User user = userService.getById(userId);
        return userService.getSafetyUser(user);
         */
        User safetyUser = userService.getCurrentUser(request);
        return ResultUtils.success(safetyUser);
    }

    @GetMapping(value = "/search")  //先不做分页
    public BaseResponse <List<User>>searchUsers(String username, HttpServletRequest request){
        if(isAdmin(request)){
           return ResultUtils.error(ErrorCode.NO_AUTH);
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if(StringUtils.isNotBlank(username)){
            queryWrapper.like("username",username);
        }
        List<User> userList = userService.list(queryWrapper);
        List<User> list = userList.stream().map(user -> userService.getSafetyUser(user)).collect(Collectors.toList());//java 8 特性
        return ResultUtils.success(list);
    }
    @PostMapping (value = "/delete")
    public BaseResponse <Boolean> deleteUser(@RequestBody long id,HttpServletRequest request){//用泛型，先给装箱一下
        if(isAdmin(request)){
            return ResultUtils.error(ErrorCode.NO_AUTH);
        }
     if(id <= 0){
         return ResultUtils.error(ErrorCode.PARAMS_ERROR);
     }
        boolean b = userService.removeById(id);
        return ResultUtils.success(b);

    }
    /**
     *  是否为管理员
     */
    private Boolean isAdmin(HttpServletRequest request ){
        //仅管理员查询
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        User user = (User) userObj;
        if(user == null||user.getUserRole() != ADMIN_ROLE){
            return false;
        }
        return  true;
    }
}
